package com.gr.dmbackend.service.Impl.sysadmin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.dmbackend.mapper.BuildingMapper;
import com.gr.dmbackend.mapper.DormaddminMapper;
import com.gr.dmbackend.model.Building;
import com.gr.dmbackend.model.Dormaddmin;
import com.gr.dmbackend.service.sysadmin.AddBuildingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class AddBuildingServiceImpl implements AddBuildingService {

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private DormaddminMapper dormaddminMapper;

    @Override
    public JSONObject addBuilding(Map<String, String> data) {

        JSONObject resp = new JSONObject();

        String name = data.get("name");
        String addminId = data.get("addminId");
        String introduce = data.get("introduce");
        String height = data.get("height");

        if (name.isEmpty()) {
            resp.put("error_message", "楼栋名不能为空");
            return resp;
        }
        if ("请选择管理员".equals(addminId)) {
            resp.put("error_message", "请选择管理员");
            return resp;
        }
        if (introduce.isEmpty()) {
            resp.put("error_message", "简介不能为空");
            return resp;
        }
        if ("请选择楼层数".equals(height)) {
            resp.put("error_message", "楼层数不能为空");
            return resp;
        }
        if (name.length() > 20) {
            resp.put("error_message", "楼栋名长度超出限制");
            return resp;
        }
        if (addminId.length() > 20) {
            resp.put("error_message", "管理员名称长度超出限制");
            return resp;
        }
        if (introduce.length() > 20) {
            resp.put("error_message", "简介长度超出限制");
            return resp;
        }
        if (height.length() > 5) {
            resp.put("error_message", "楼层数长度超出限制");
            return resp;
        }

        QueryWrapper<Dormaddmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_id", addminId);
        String addmin = dormaddminMapper.selectOne(queryWrapper).getName();

        QueryWrapper<Building> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name", name);
        Building item = buildingMapper.selectOne(queryWrapper1);
        if (item != null) {
            resp.put("error_message", "楼栋已存在");
            return resp;
        }

        Building building = new Building();
        building.setName(name);
        building.setAddminId(addminId);
        building.setAddmin(addmin);
        building.setIntroduce(introduce);
        building.setHeight(height);
        buildingMapper.insert(building);
        resp.put("error_message", "success");

        return resp;
    }
}
